Null Object
It uses a special instance of a class that acts as a default or null object, eliminating the need for null checks in the code. Instead of returning null or an empty value, the pattern provides a neutral object that implements the same interface as the other objects, allowing methods to be called without checking for null.
Structure
Subject Interface: Defines the behavior that concrete objects must implement.Real Object: A concrete implementation of the subject interface that performs the intended behavior.Null Object: A concrete implementation of the subject interface that does nothing or provides default behavior.
Example
// Subject Interface
interface Logger {
void log(String message);
}
// Real Object
class ConsoleLogger implements Logger {
@Override
public void log(String message) {
System.out.println("ConsoleLogger: " + message);
}
}
// Null Object
class NullLogger implements Logger {
@Override
public void log(String message) {
// Do nothing
}
}
// Client Class
class Application {
private Logger logger;
// Constructor that accepts a logger
public Application(Logger logger) {
this.logger = logger != null ? logger : new NullLogger(); // Use NullLogger if logger is null
}
public void run() {
logger.log("Application is starting...");
// Other application logic
logger.log("Application is running...");
}
}
// Main Class
public class Main {
public static void main(String[] args) {
// Using a real logger
Logger consoleLogger = new ConsoleLogger();
Application appWithLogger = new Application(consoleLogger);
appWithLogger.run();
// Using a null logger
Application appWithoutLogger = new Application(null);
appWithoutLogger.run();
}
}